package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IPermissionService permissionService;

    //查询全部方法
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo pageResult = roleService.query(qo);
        model.addAttribute("pageResult", pageResult);
        return "role/list";
    }

    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                roleService.deleteByPrimaryKey(id);
            }
            return new JsonResult(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "删除失败");
        }

    }

    //新增 或 修改
    @RequestMapping("/input")
    public String input(Long id, Model model) {

        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);

        if (id != null) {
            //表示去修改
            Role role = roleService.selectByPrimaryKey(id);
            model.addAttribute("role", role);
        }
        return "role/input";// 让 浏览器重新 发一次请求 跳转到input 页面
    }

    // 新增 或 修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() != null) {
            //新增
            roleService.updateByPrimaryKey(role, ids);
            System.out.println(role);
        } else {
            roleService.insert(role, ids);
        }
        return "redirect:/role/list.do";
    }

}
